<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/16 0016
 * Time: 14:23
 */

namespace app\api\controller\v1\agent;


use app\api\controller\v1\Agent;
use app\currency\service\AgentRebateService;
use app\currency\service\DateService;
use think\Db;

class Profit extends Agent
{
    /**
     * 收益记录
     * modal:service\bind
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data = $this->_input([
            'modal' => $this->request->get('modal'),
            'month' => $this->request->get('month')
        ]);
        in_array($data['modal'],['all','service','bind']) || $data['modal'] = 'all';
        if(empty($data['month']) || DateService::checkDateMonthFormat($data['month']) === false)
        {
            $data['month'] = date('Y-m');
        }
        list($start_at,$end_at) = [
            date('Y-m-d H:i:s', mktime(00, 00, 00, date('m', strtotime($data['month'])), 01)),
            date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', strtotime($data['month']))+1, 00))
        ];
        $group = AgentRebateService::getRoyaltyListByDay($this->aid, $data['modal'], $start_at, $end_at);
        if($group)
        {
            foreach ($group as &$item) {
                $item['total_amount'] = Db::name('AgentRebate')
                    ->whereIn('id',$item['ids'])
                    ->sum('amount');
                $item['list'] = Db::name('AgentRebate')
                    ->alias('a')
                    ->leftJoin('cleaner b','a.cid = b.id')
                    ->leftJoin('member c','a.mid = c.id')
                    ->whereIn('a.id',$item['ids'])
                    ->field('a.*,b.name cleaner_name,b.work_headimg,c.nickname,c.headimg')
                    ->select();
            }
        }
        $this->success('获取收益记录成功！', $group);
    }
}